package com.java.common.utils;

import com.java.common.constants.ResultCodeEnum;
import lombok.*;
import lombok.experimental.Accessors;

import java.io.Serializable;


/**
 * 响应信息主体
 */
@ToString
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class R<T> implements Serializable {
	private static final long serialVersionUID = 1L;

	private int code;

	private String msg;

	private T data;

	public static <T> R<T> ok() {
		return restResult(null, ResultCodeEnum.SUCCESS.getCode(), null);
	}

	public static <T> R<T> ok(T data) {
		return restResult(data, ResultCodeEnum.SUCCESS.getCode(), null);
	}

	public static <T> R<T> ok(T data, String msg) {
		return restResult(data, ResultCodeEnum.SUCCESS.getCode(), msg);
	}

	public static <T> R<T> error(String msg) {
		return restResult(null, ResultCodeEnum.ERROR.getCode(), msg);
	}

	public static <T> R<T> error(ResultCodeEnum e) {
		return restResult(null, e.getCode(), e.getMessage());
	}

	private static <T> R<T> restResult(T data, int code, String msg) {
		R<T> apiResult = new R<T>();
		apiResult.setCode(code);
		apiResult.setData(data);
		apiResult.setMsg(msg);
		return apiResult;
	}

}

